<?php
/**
 * Created by PhpStorm.
 * User: function
 * Date: 2018-04-14
 * Time: 10:13
 */

namespace app\api\controller\v1;
use app\common\logic\MallLogic;
use app\common\logic\MemberLogic;
use app\common\controller\Api;
use auth\OAuthLoginClass;
use think\Session;
use think\Cache;
use app\common\model\Member as MemberModel;
class Member extends Api
{
    protected $authenticate=['except'=>'register,login,forgotpwd,getauthurl,snslogin,getwxopenid'];
    
    protected $phone_reg_rule = [
        'phone|手机号'  =>  'require',
        'password|密码' =>  'require',
//        'code|验证码' =>  'require',
//        'validate_token|验证码标识' =>  'require',
    ];
    protected $phone_login_rule = [
        'phone|手机号'  =>  'require',
        'password|密码' =>  'require',
//        'code|验证码' =>  'require',
//        'validate_token|验证码标识' =>  'require',
    ];
    
    protected $snslogin_wap_rule = [
        'channel|渠道类型' => 'require',
        'code' => 'require',
        'state' => 'require',
    ];
    
    
    
    public function index(){
    
        
        $id = $this->getUserId();
        
        $params = paramForm();
        if(isset($params['action'])&&$params['action']=='ext'){
            $this->ext($id);
            die;
        }
        
        $logic = new MemberLogic();
        $self = $logic->findModel($id);
        success($self);
    }
    
    public function login(){
        
        $logic =new MemberLogic();
        $params = paramForm();
        $post = $this->setPost($params,'phone,password');
        $this->validate($post,$this->phone_login_rule);//表单校验
        $rt = $logic->login($post);
      
        if($rt['code']){
            success($rt['data']);
        }else{
            error($rt['msg']?$rt['msg']:'登陆失败');
        }
        
    }
    
    /**
     * 手机号+密码注册
     */
    public function register(){
        
        $logic =new MemberLogic();
        $params = paramForm();
        $post = $this->setPost($params,'phone,code,password,validata_token');
        
        $this->validate($post,$this->phone_reg_rule);//表单校验
        
        if(!isMobile($post['phone']))error('手机号码格式不对');
        $params['nickname'] = '用户'.time();
        $rt = $logic->add($post);
        
        if($rt){
            success('注册成功');
        }else{
            error('注册失败');
        }
        
    }
    
    /**
     * @param $channel
     * @param $code
     * @param $state
     */
    public function getWXopenId($channel,$code,$state){
        
        $rule = [
            'channel' => 'require',
            'code' => 'require',
            'state' => 'require',
        ];
        
        $msg = [
            'channel.require' => '渠道类型必须填写',
            'code.require' => 'code必须填写',
            'state.require' => 'state必须填写',
        ];
        
        $params = paramForm();//转化参数
        $this->validate($params,$rule);//表单校验
        
        
        switch ($channel) {
            //为后续其他渠道留好位置。。。
            case 'wechat_pub_pay':
                $userInfo = OAuthLoginClass::authLogin('wechat_pub', $code, $state);
                
                //如果是微信已经绑定过其他用户，就不要跟着弄了。只要返回oepnid让支付就好了。但是后续其他地方注意，open_id可能存的不是自己的，不能使用她来做什么。而且微信支付对账的时候也要注意这一点。可能出现open_id不是自己当前账户绑定的。
                $isHas = MemberModel::get(['wx_pub_openid'=>$userInfo['openid']]);
                if($isHas){
                    api(1,'该微信已经绑定过其他用户了',$userInfo['openid']);
                    //error('该微信已经绑定过其他用户了');
                }
                $logic = new MemberLogic();
                $logic->changeInfo($this->getUserId(),'wx_pub_openid',$userInfo['openid']);
                success($userInfo['openid']);
                break;
            default:
                error("参数失败");
                break;
        }
    }
    
    /**
     * @desc 第三方账号统一登陆接口
     * @param $channel
     * @param $code
     * @param $state
     */
    public function snsLogin(){
        
        $params = paramForm();
        $logic = new MemberLogic();
        
        $this->validate($params,$this->snslogin_wap_rule);
        $loginRT = $logic->snsLogin($channel = $params['channel'],$code = $params['code'],$state = $params['state']);

        if(!$loginRT['code']){
            error($loginRT['msg']);
        }
        
        success($loginRT['data']);
        
    }
    
    /**
     *
     * @desc 第三方账号统一获取auth 的redirect地址的接口
     * @param $channel
     * @param $callback
     */
    
    public function getAuthUrl(){
        
        $rule = [
            'channel' => 'require',
        ];
        
        $msg = [
            'channel.require' => '渠道类型必须填写',
        ];
        
        $params = paramForm();//转化参数
        $this->validate($params,$rule);//表单校验
        $channel = $params['channel'];
        switch ($channel){
            case 'wap_all':
                $redirectUrl = array();
                $redirectUrl['wechat_wap'] = OAuthLoginClass::GetCodeUrl('wechat_wap');
                $redirectUrl['wechat_pub'] = OAuthLoginClass::GetCodeUrl('wechat_pub');
                $redirectUrl['weibo_wap'] = OAuthLoginClass::GetCodeUrl('weibo_wap');
                $redirectUrl['qq_wap'] = OAuthLoginClass::GetCodeUrl('qq_wap');
                break;
            case 'wechat_pub_pay':
                $redirectUrl = OAuthLoginClass::GetCodeUrl('wechat_pub_pay');
                break;
            case 'wechat_pub':
                $redirectUrl = OAuthLoginClass::GetCodeUrl('wechat_pub');
                break;
//            case 'wechat_app':
//                $redirectUrl = OAuthLoginClass::GetCodeUrl('wechat_app');
//                break;
            case 'wechat_wap':
                $redirectUrl = OAuthLoginClass::GetCodeUrl('wechat_wap');
                break;
            case 'weibo_app':
                $redirectUrl = OAuthLoginClass::GetCodeUrl('weibo_app');
            case 'weibo_wap':
                $redirectUrl = OAuthLoginClass::GetCodeUrl('weibo_wap');
                break;
            case 'qq_app':
                $redirectUrl = OAuthLoginClass::GetCodeUrl('qq_app');
                break;
            case 'qq_wap':
                $redirectUrl = OAuthLoginClass::GetCodeUrl('qq_wap');
                break;
            default:
                error('channel参数错误');
                break;
        }
        
        api(1,'获取跳转链接成功',$redirectUrl);
        
    }
    
    
    public function bindPhone(){
        
        $rule = [
            'phone'  => 'require|max:11',
            'code'   => 'require',
            'BizId'=>'require'
        ];
        
        $msg = [
            'phone.require' => '名称必须',
            'phone.max' => '手机号位数不对',
            'code.require' => '验证码必填',
            'BizId.require' => '短信回执id必填',
        ];
        
        $params = paramForm();//转化你参数
        $params['BizId'] = Session::get('smsid');
        $this->validate($params,$rule);//表单校验
        if(!isMobile($params['phone'])){
            error('短信发送失败,手机号码格式不对');
        };
        
        
        $this->checkPhoneCode($params['BizId'],$params['code']);//校验验证码是否正确
        
        $logic = new MemberLogic();
        
        $result = $logic->changeInfo($this->getUserId(),'phone',$params['phone']);
        
        if($result){
            api(1,'绑定手机号码成功',null);
        }else{
            error('手机号码绑定失败');
        }
        
    }
    
    public function changeInfo(){
        $params = paramForm();
        
        //去掉敏感的字段

        if(isset($params['password'])){
            unset($params['password']);
        }
        if(isset($params['passsalt'])){
            unset($params['passsalt']);
        }
        if(isset($params['id'])){
            unset($params['id']);
        }
        if(isset($params['pionts_num'])){
            unset($params['pionts_num']);
        }
        if(isset($params['cashing_money'])){
            unset($params['cashing_money']);
        }
        

        
        //处理下各种渠道切换头像的问题
        if(isset($params['headimgurl'])){
            if(isset($params['channel'])&&$params['channel']=='wx_pub'){
                $wxDevConfig = config('thirdaccount.WeChatDeveloper');
                $wechat = new \WeChat\Media($wxDevConfig);
                $wechat->delAccessToken();
                
                //获取微信的素材
                $serverId = $params['headimgurl'];
                $result = $wechat->get($serverId);
    
                // 处理执行的结果
                if ($result === FALSE) {
                    // 接口失败的处理
                    error('获取微信临时文件资源失败');
                } else {
                    $filename = uniqid() . '.jpg';            //定义图片名字及格式
                    $tempFile = saveFile($filename, $result);
                    $file = new \think\File($tempFile);
        
                    if ($file) {
                        $file->setUploadInfo(['name' => $filename]);
                        $oss_url = $this->uploadToAlyun($file);
                        $params['headimgurl'] = $oss_url;
                    } else {
                        error('上传文件缺失');
                    }
        
                }
                
            }else{
                
                $headimgurl = request()->file('headimgurl');
                if($headimgurl){
                    $params['headimgurl'] = $this->uploadToAlyun($headimgurl);
                }else{
                    error('头像必传');
                }
            }
        }
        
        $logic = new MemberLogic();
        $rt = $logic->edit($this->getUserId(),$params);
        
        if($rt){
            success('修改成功');
        }else{
            error('修改失败');
        }
    }
    
    
    public function avatar($userid){
        $logic = new MemberLogic();
        $member = $logic->findModel($userid);
        echo $logic->headimgurl;
    }
    
    
    public function ext(){
       
        $logic = new MemberLogic();
        $extInfo = $logic->getExtInfo($this->getUserId());
        success($extInfo);
//        freeze_money 冻结？
//        cashing_money 可提现
//        cashed_money 已提现
//        $user['cash'] = null;
//
//        $user['record'] = null;
        
    }
    
}